import 'package:flutter/material.dart';
import 'PageWidget.dart';
import 'package:english_words/english_words.dart';
import 'package:flutter_app/ActionBarWidget.dart';
import 'package:flutter_app/Header1.dart';
import 'package:flutter_app/Header2.dart';
import 'CustomScrollViewRoute.dart';
import 'Toast.dart';
import 'common/NetUtil.dart';
import 'package:dio/dio.dart';
import 'models/BaseResponse.dart';
import 'package:flutter_app/models/FuLi.dart';
import 'widgets/GirlImages.dart';
import 'widgets/DeviceInfoWidget.dart';
import 'widgets/AnimationTextWidget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'TestSP.dart';
import 'package:flutter_app/HomeWidget.dart';
import 'package:flutter_app/LoginWidget.dart';
import 'scoped/ScopedOne.dart';
import 'scoped/CountModel.dart';
import 'package:scoped_model/scoped_model.dart';

//import 'package:flutter_app/NetUtil.dart';
import 'package:flutter_app/common/ApiInterface.dart';

import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:flutter_app/redux/CountState.dart';
import 'package:flutter_app/redux/ReduxOne.dart';
import 'package:flutter_app/bloc/BLoCOne.dart';

void main() {
  final store =
      Store<CountState>(reducer, initialState: CountState.initState());
  return runApp(MyApp(store));
}

class MyApp extends StatelessWidget {
  CountModel countModel = CountModel();

  final Store<CountState> store;

  MyApp(this.store);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
// 测试scoped  ↓↓两行↓↓
//    return ScopedModel<CountModel>(
//      model: countModel,
// 测试redux   ↓↓两行↓↓
    return StoreProvider<CountState>(
      store: store,
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          // This is the theme of your application.
          //
          // Try running your application with "flutter run". You'll see the
          // application has a blue toolbar. Then, without quitting the app, try
          // changing the primarySwatch below to Colors.green and then invoke
          // "hot reload" (press "r" in the console where you ran "flutter run",
          // or simply save your changes to "hot reload" in a Flutter IDE).
          // Notice that the counter didn't reset back to zero; the application
          // is not restarted.
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(title: new WordPair.random().toString()),
      ),
    );
//    return MaterialApp(
//      title: 'Flutter Demo',
//      theme: ThemeData(
//        // This is the theme of your application.
//        //
//        // Try running your application with "flutter run". You'll see the
//        // application has a blue toolbar. Then, without quitting the app, try
//        // changing the primarySwatch below to Colors.green and then invoke
//        // "hot reload" (press "r" in the console where you ran "flutter run",
//        // or simply save your changes to "hot reload" in a Flutter IDE).
//        // Notice that the counter didn't reset back to zero; the application
//        // is not restarted.
//        primarySwatch: Colors.blue,
//      ),
//      home: MyHomePage(title: new WordPair.random().toString()),
//    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  DateTime _lastPressedAt; //上次点击时间

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  void _jian() {
    setState(() {
      _counter--;
    });
  }

  void _guiling() {
    setState(() {
      _counter = 0;
    });
  }

  void _chongzhi() {
    setState(() {
      _counter = 10;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return WillPopScope(
      onWillPop: () async {
        if (_lastPressedAt == null ||
            DateTime.now().difference(_lastPressedAt) > Duration(seconds: 1)) {
          _lastPressedAt = DateTime.now();
          Toast.toast(context, "再次点击返回键退出应该！");
          return false;
        }
        return true;
      },
      child: Scaffold(
        appBar: AppBar(
          // Here we take the value from the MyHomePage object that was created by
          // the App.build method, and use it to set our appbar title.
          title: Text(widget.title),
        ),

        body: SingleChildScrollView(
          // Center is a layout widget. It takes a single child and positions it
          // in the middle of the parent.
          child: Column(
            // Column is also layout widget. It takes a list of children and
            // arranges them vertically. By default, it sizes itself to fit its
            // children horizontally, and tries to be as tall as its parent.
            //
            // Invoke "debug painting" (press "p" in the console, choose the
            // "Toggle Debug Paint" action from the Flutter Inspector in Android
            // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
            // to see the wireframe for each widget.
            //
            // Column has various properties to control how it sizes itself and
            // how it positions its children. Here we use mainAxisAlignment to
            // center the children vertically; the main axis here is the vertical
            // axis because Columns are vertical (the cross axis would be
            // horizontal).
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
//              Header1(),
//              Header2(),
              ActionBarWidget(
                title: "我的主页" * 6,
                right: "添加",
              ),
              Flex(
                direction: Axis.horizontal,
                children: <Widget>[
                  Expanded(
                    flex: 2,
                    child: Padding(
                      padding: const EdgeInsets.all(20.0),
                      child: Text("我是Padding000"),
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: Text("第一个",
                        style: TextStyle(
                            color: Colors.yellow,
                            background: new Paint()..color = Colors.redAccent)),
                  ),
                  Expanded(flex: 3, child: Text("第二个")),
                ],
              ),
              Text(
                'You have pushed the button this many times:' * 3,
                textAlign: TextAlign.center,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
//              textScaleFactor: 1.2,
                style: TextStyle(
                    color: Colors.red,
                    fontSize: 16,
                    height: 1.2,
//                fontFamily: "Courier",//字体
                    background: new Paint()..color = Colors.yellow,
                    decoration: TextDecoration.underline),
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.display1,
              ),
              Text("Hello！！！"),
              ListView(
                shrinkWrap: true,
//              padding: const EdgeInsets.all(20.0),
                padding: const EdgeInsets.only(left: 20.0),
                children: <Widget>[
                  const Text(
                    'I\'m dedicating every day to you',
                    textScaleFactor: 2.0,
                  ),
                  const Text('Domestic life was never quite my style'),
                  const Text('When you smile, you knock me out, I fall apart'),
                  const Text(
                    'And I thought I was so smart',
                    style: TextStyle(
                        color: Colors.green,
                        fontSize: 20,
                        fontFamily: 'Raleway'),
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset(
                    "images/ic_pay_jiaohang.png",
                    width: 60,
                  ),
                  Image.asset(
                    "images/ic_pay_zhaohang.png",
                    width: 60,
                  ),
                  Image.asset(
                    "images/ic_pay_zhifubao.png",
                    width: 60,
                  ),
                  Image.asset(
                    "images/ic_pay_zhonghang.png",
                    width: 60,
                  ),
                  Image.asset(
                    "images/ic_pay_gonghang.png",
                    width: 60,
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  RaisedButton(
                    child: Text("美女"),
                    color: Colors.blue,
                    onPressed: () {
//                      NetUtil.getJson("", paras)
//                      ApiInterface.getFuli().then((data) {
//                        print(data);
//                      }).catchError((errorMsg) {
//                        print(errorMsg);
//                        if (errorMsg is LogicError) {
//                          print("1234");
//                        } else {
//                          print("5678");
//                        }
//                      });
                      getFuli();
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => new GirlImages()));
                    },
                  ),
                  FlatButton(
                    child: Text("列表1"),
                    color: Colors.yellow,
//              highlightColor: Colors.blue[700],
//              colorBrightness: Brightness.dark,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.0)),
//                  onPressed: _guiling,
                    onPressed: () {
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) =>
                                  new CustomScrollViewRoute()));
                    },
                  ),
                  OutlineButton(
                    child: Text("列表2"),
                    color: Colors.redAccent,
//              textColor: Colors.green,

                    disabledBorderColor: Colors.redAccent,
                    highlightColor: Colors.yellow,
//                  onPressed: _chongzhi,
                    onPressed: () {
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => new PageWidget(
                                    title: "将进酒",
                                  )));
                    },
                  ),
                  RaisedButton(
                    child: Text("SP"),
                    onPressed: () {
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => new TestSP()));
                    },
                  )
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  RaisedButton(
                    child: Text("首页"),
                    color: Colors.blue,
                    onPressed: () {
//                      NetUtil.getJson("", paras)
//                      ApiInterface.getFuli().then((data) {
//                        print(data);
//                      }).catchError((errorMsg) {
//                        print(errorMsg);
//                        if (errorMsg is LogicError) {
//                          print("1234");
//                        } else {
//                          print("5678");
//                        }
//                      });
                      getFuli();
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => new HomeWidget()));
                    },
                  ),
                  FlatButton(
                    child: Text("登录"),
                    color: Colors.yellow,
//              highlightColor: Colors.blue[700],
//              colorBrightness: Brightness.dark,
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(20.0)),
//                  onPressed: _guiling,
                    onPressed: () {
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => new LoginWidget()));
                    },
                  ),
                  OutlineButton(
                    child: Text("重置"),
                    color: Colors.redAccent,
//              textColor: Colors.green,

                    disabledBorderColor: Colors.redAccent,
                    highlightColor: Colors.yellow,
//                  onPressed: _chongzhi,
                    onPressed: () {
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => new PageWidget(
                                    title: "将进酒",
                                  )));
                    },
                  ),
                  RaisedButton(
                    child: Text("SP"),
                    onPressed: () {
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => new TestSP()));
                    },
                  )
                ],
              ),
              Text(
                "状态管理",
                style: TextStyle(
                  color: Colors.cyan,
                  fontSize: 14,
                ),
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  RaisedButton(
                    child: Text("Scoped"),
                    color: Colors.red[200],
                    onPressed: () {
                      //todo
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => new ScopedOne()));
                    },
                  ),
                  RaisedButton(
                    child: Text("Redux"),
                    color: Colors.blue[200],
                    onPressed: () {
                      //todo
                      Navigator.push(
                          context,
                          new MaterialPageRoute(
                              builder: (context) => new ReduxOne()));
                    },
                  ),
                  RaisedButton(
                    child: Text("BLoC"),
                    color: Colors.orange[200],
                    onPressed: () {
                      //todo
                      Navigator.push(context,
                          MaterialPageRoute(builder: (context) => BLoCOne()));
                    },
                  ),
                  RaisedButton(
                    child: Text("Other"),
                    color: Colors.green[200],
                    onPressed: () {
                      //todo
                    },
                  )
                ],
              )
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
//          onPressed: _incrementCounter,
          onPressed: () {
            Navigator.push(
                context,
                new MaterialPageRoute(
                    builder: (context) => new AnimationTextWidget()));
          },
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ), // This trailing comma makes auto-formatting nicer for build methods.
      ),
    );
  }
}

void getFuli() async {
  try {
    Dio dio = new Dio();
    Options options = new Options(
        baseUrl: "http://gank.io/api/data/福利",
        connectTimeout: 5000,
        receiveTimeout: 5000);
    dio.options = options;
    Future future = dio.get("/10/1");
    future.then((data) {
      print(data);
      FuLi fuLi = new FuLi.fromJson(data.data);
      print(fuLi.results);
    }).catchError((error) {
      print(error);
    });
//    Response response;
//    response = await Dio().get("http://gank.io/api/data/福利/10/1");
//    return print(response);
  } catch (e) {
    return print(e);
  }
}
